/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.catalina.startup;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.catalina.security.SecurityClassLoad;
import org.apache.catalina.startup.ClassLoaderFactory.Repository;
import org.apache.catalina.startup.ClassLoaderFactory.RepositoryType;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

/**
 * Bootstrap loader for Catalina.  This application constructs a class loader
 * for use in loading the Catalina internal classes (by accumulating all of the
 * JAR files found in the "server" directory under "catalina.home"), and
 * starts the regular execution of the container.  The purpose of this
 * roundabout approach is to keep the Catalina internal classes (and any
 * other classes they depend on, such as an XML parser) out of the system
 * class path and therefore not visible to application level classes.
 *
 * @author Craig R. McClanahan
 * @author Remy Maucherat
 */
public final class Bootstrap {

    private static final Log log = LogFactory.getLog(Bootstrap.class);

    /**
     * Daemon object used by main.
     * 守护进程使用的主要对象
     */
    //初始化并发锁
    private static final Object daemonLock = new Object();
    //单例
    private static volatile Bootstrap daemon = null;
    //jvm启动参数catalina.base
    private static final File catalinaBaseFile;
    //jvm启动参数catalina.home
    private static final File catalinaHomeFile;

    private static final Pattern PATH_PATTERN = Pattern.compile("(\"[^\"]*\")|(([^,])*)");

    //Tomcat目录结构如下：
    //bin (运行脚本）、conf (配置文件）、 lib (核心库文件） 、logs (日志目录）、temp (临时目录）、
    //webapps (自动装载的应用程序的目录）、work (JVM临时文件目录[java.io.tmpdir])
    //其中只有 bin 和 lib 目录被多个tomcat实例公用，其它目录conf、logs、temp、webapps和work 每个Tomcat实例必须拥有其自己独立的备份。
    //catalina.home和catalina.base的用途:
    //catalina.home(安装目录)：指向公用信息的位置，就是bin和lib的父目录。
    //catalina.base(工作目录)：指向每个Tomcat目录私有信息的位置，就是conf、logs、temp、webapps和work的父目录。
    //简单的说，CATALINA_HOME是Tomcat的安装目录，CATALINA_BASE是Tomcat的工作目录。如果我们想要运行Tomcat的 多个实例，但是不想安装多个Tomcat软件副本。那么我们可以配置多个工作 目录，每个运行实例独占一个工作目录，但是共享同一个安装目录。
    //Tomcat每个运行实例需要使用自己的conf、logs、temp、webapps、work和shared目录，因此CATALINA_BASE就 指向这些目录。 而其他目录主要包括了Tomcat的二进制文件和脚本，CATALINA_HOME就指向这些目录。
    //如果我们希望再运行另一个Tomcat实例，那么我们可以建立一个目录，把conf、logs、temp、webapps、work和shared拷贝 到该目录下，然后让CATALINA_BASE指向该目录即可

    //在启动过程中，首先会调用该静态方法，将参数catalina.base和catalina.home存放在System的Properties中。
    static {
        // Will always be non-null
        //tomcat所在目录 G:\tomcat
        String userDir = System.getProperty("user.dir");

        // Home first
        //系统属性中是否设置catalina.home，为了源码的正常启动我们在jvm中设置了该路径 默认情况下为null
        String home = System.getProperty(Constants.CATALINA_HOME_PROP);
        File homeFile = null;
        //homeFile不为null，那么就是该路径为准
        if (home != null) {
            File f = new File(home);
            try {
                // 返回此抽象路径名的规范形式
                homeFile = f.getCanonicalFile();
            } catch (IOException ioe) {
                homeFile = f.getAbsoluteFile();
            }
        }
        //如果没有设置，即homeFile为null，那我们就是bootstrap.jar中寻找（源码中没有该jar包，所以需要配置catalina.home的值）
        if (homeFile == null) {
            // First fall-back. See if current directory is a bin directory
            // in a normal Tomcat install
            File bootstrapJar = new File(userDir, "bootstrap.jar");

            if (bootstrapJar.exists()) {
                File f = new File(userDir, "..");
                try {
                    homeFile = f.getCanonicalFile();
                } catch (IOException ioe) {
                    homeFile = f.getAbsoluteFile();
                }
            }
        }
        //如果此时仍然为空，那么让其为tomcat的使用目录
        if (homeFile == null) {
            // Second fall-back. Use current directory
            File f = new File(userDir);
            try {
                homeFile = f.getCanonicalFile();
            } catch (IOException ioe) {
                homeFile = f.getAbsoluteFile();
            }
        }

        catalinaHomeFile = homeFile;
        //设置到系统属性中
        System.setProperty(
                Constants.CATALINA_HOME_PROP, catalinaHomeFile.getPath());

        // Then base
        //系统属性中是否设置catalina.base 如果没有多实例的时候则让其和home路径一致
        String base = System.getProperty(Constants.CATALINA_BASE_PROP);
        if (base == null) {
            catalinaBaseFile = catalinaHomeFile;
        } else {
            File baseFile = new File(base);
            try {
                baseFile = baseFile.getCanonicalFile();
            } catch (IOException ioe) {
                baseFile = baseFile.getAbsoluteFile();
            }
            catalinaBaseFile = baseFile;
        }
        System.setProperty(
                Constants.CATALINA_BASE_PROP, catalinaBaseFile.getPath());
    }

    // -------------------------------------------------------------- Variables


    /**
     * Daemon reference.
     */
    //catalina 实例
    private Object catalinaDaemon = null;
    //公共类加载器，catalinaLoader，sharedLoader两者共同引用的,加载路径中的class可以被Tomcat容器本身以及各个Webapp访问
    ClassLoader commonLoader = null;
    //tomcat的jvm类加载器,加载路径中的class对于Webapp不可见,仅对tomcat容器可见
    ClassLoader catalinaLoader = null;
    //共享类加载器，加载路径中的class对于所有Webapp可见，但是对于Tomcat容器不可见
    ClassLoader sharedLoader = null;


    // -------------------------------------------------------- Private Methods

    //4:WebAppClassLoader：以Shared类加载器为父类，加载/WEB-INF/classes目录下的未压缩的Class和资源文件以及/WEB-INF/lib目录下的jar包，
    //该类加载器只对当前Web应用可见，对其他Web应用均不可见
    //注意：默认情况下，Common、Catalina、Shared类加载器是同一个，但可以配置3个不同的类加载器，使他们各司其职。
    //首先，Common类加载器负责加载Tomcat应用服务器内部和Web应用均可见的类，如Servlet规范相关包和一些通用工具包。
    //其次，Catalina类加载器负责只有Tomcat应用服务器内部可见的类，这些类对Web应用不可见。比如，想实现自己的会话存储方案，而且该方案依赖了一些第三方包，
    //当然是不希望这些包对Web应用可见，这时可以配置server.load，创建独立的Catalina类加载器。
    //再次，Shared类负责加载Web应用共享类，这些类tomcat服务器不会依赖(不可见)。
    private void initClassLoaders() {
        try {
            //1:以应用类加载器为父类，是tomcat顶层的公用类加载器，其路径由conf/catalina.properties中的common.loader指定，默认指向${catalina.home}/lib下的包
            commonLoader = createClassLoader("common", null);
            if (commonLoader == null) {
                // no config file, default to this loader - we might be in a 'single' env.
                //如果common类加载器没有创建成功，那么获取当前类的加载器进行赋值
                commonLoader = this.getClass().getClassLoader();
            }
            //2:以Common类加载器为父类，是用于加载Tomcat应用服务器的类加载器，其路径由server.loader指定，默认为空，此时tomcat使用Common类加载器加载应用服务器
            catalinaLoader = createClassLoader("server", commonLoader);
            //3:以Common类加载器为父类，是所有Web应用的父类加载器，其路径由shared.loader指定，默认为空，此时tomcat使用Common类加载器作为Web应用的父加载器。
            sharedLoader = createClassLoader("shared", commonLoader);
        } catch (Throwable t) {
            handleThrowable(t);
            log.error("Class loader creation threw exception", t);
            System.exit(1);
        }
    }


    private ClassLoader createClassLoader(String name, ClassLoader parent)
        throws Exception {
        // 获取指定类加载器的加载jar包路径  默认：conf/catalina.properties
        // common.loader路径为${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar 剩余的两个默认为空
        String value = CatalinaProperties.getProperty(name + ".loader");
        //如果获取的路径值为null，直接返回父类加载器
        if ((value == null) || (value.equals(""))) {
            return parent;
        }
        //将路径中的${}换成具体的路径值
        value = replace(value);

        List<Repository> repositories = new ArrayList<>();
        // 解析属性路径变量为仓库路径数组
        String[] repositoryPaths = getPaths(value);
        // 对每个仓库路径进行repositories设置。我们可以把repositories看成一个个待加载的位置对象，可以是一个classes目录，一个jar文件目录等等
        for (String repository : repositoryPaths) {
            // Check for a JAR URL repository
            try {
                @SuppressWarnings("unused")
                URL url = new URL(repository);
                repositories.add(new Repository(repository, RepositoryType.URL));
                continue;
            } catch (MalformedURLException e) {
                // Ignore
            }

            // Local repository
            if (repository.endsWith("*.jar")) {
                repository = repository.substring
                    (0, repository.length() - "*.jar".length());
                repositories.add(new Repository(repository, RepositoryType.GLOB));
            } else if (repository.endsWith(".jar")) {
                repositories.add(new Repository(repository, RepositoryType.JAR));
            } else {
                repositories.add(new Repository(repository, RepositoryType.DIR));
            }
        }
        // 使用类加载器工厂创建一个类加载器
        return ClassLoaderFactory.createClassLoader(repositories, parent);
    }


    /**
     * System property replacement in the given string.
     *
     * @param str The original string
     * @return the modified string
     */
    protected String replace(String str) {
        // Implementation is copied from ClassLoaderLogManager.replace(),
        // but added special processing for catalina.home and catalina.base.
        String result = str;
        int pos_start = str.indexOf("${");
        if (pos_start >= 0) {
            StringBuilder builder = new StringBuilder();
            int pos_end = -1;
            while (pos_start >= 0) {
                builder.append(str, pos_end + 1, pos_start);
                pos_end = str.indexOf('}', pos_start + 2);
                if (pos_end < 0) {
                    pos_end = pos_start - 1;
                    break;
                }
                //propName为${}中包含的变量名称
                String propName = str.substring(pos_start + 2, pos_end);
                String replacement;
                if (propName.length() == 0) {
                    replacement = null;
                } else if (Constants.CATALINA_HOME_PROP.equals(propName)) {
                    replacement = getCatalinaHome();
                } else if (Constants.CATALINA_BASE_PROP.equals(propName)) {
                    replacement = getCatalinaBase();
                //如果二者都不是，那么去系统属性中寻找匹配
                } else {
                    replacement = System.getProperty(propName);
                }
                if (replacement != null) {
                    builder.append(replacement);
                } else {
                    builder.append(str, pos_start, pos_end + 1);
                }
                pos_start = str.indexOf("${", pos_end + 1);
            }
            builder.append(str, pos_end + 1, str.length());
            result = builder.toString();
        }
        return result;
    }


    /**
     * Initialize daemon.
     * @throws Exception Fatal initialization error
     */
    public void init() throws Exception {
        //创建了3个类加载器commonloader,catalinaLoader,sharedLoader
        initClassLoaders();
        //设置当前线程上下文环境classLoader为catalinaLoader。
        Thread.currentThread().setContextClassLoader(catalinaLoader);
        //catalinaLoader加载需要的类
        SecurityClassLoad.securityClassLoad(catalinaLoader);

        // Load our startup class and call its process() method
        if (log.isDebugEnabled()) {
            log.debug("Loading startup class");
        }
        //通过反射的方式获取Catalina类的class对象
        Class<?> startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.Catalina");
        //获取其无参构造函数进行实例化
        Object startupInstance = startupClass.getConstructor().newInstance();

        // Set the shared extensions class loader
        if (log.isDebugEnabled()) {
            log.debug("Setting startup class properties");
        }
        //初始化方法名称，方法参数信息
        String methodName = "setParentClassLoader";
        Class<?> paramTypes[] = new Class[1];
        paramTypes[0] = Class.forName("java.lang.ClassLoader");
        Object paramValues[] = new Object[1];
        paramValues[0] = sharedLoader;
        //根据方法名称，参数类型得到Catalina类的class对象中符合条件的方法信息
        Method method =
            startupInstance.getClass().getMethod(methodName, paramTypes);
        //执行该方法，设置Catalina.java的父加载器为sharedLoader
        method.invoke(startupInstance, paramValues);
        // 创建的Catalina类实例赋值给全局变量catalinaDaemon，保证在load和start方法中使用的是同一个catalina对象
        // 这样在load方法中创建的server，service，connector,engin,host等组件对象因为跟catalina绑定了层级关系  所以可以在start方法中直接获取并使用这些创建的组件实例
        catalinaDaemon = startupInstance;
    }


    /**
     * Load daemon.
     */
    private void load(String[] arguments) throws Exception {

        // Call the load() method
        String methodName = "load";
        Object param[];
        Class<?> paramTypes[];
        //根据命令行参数，来组装相应的参数信息
        if (arguments==null || arguments.length==0) {
            paramTypes = null;
            param = null;
        } else {
            //如果命令行参数不为空，会调用load(String args[])方法，通过其中的arguments(args)方法来初始化命令行参数
            paramTypes = new Class[1];
            paramTypes[0] = arguments.getClass();
            param = new Object[1];
            param[0] = arguments;
        }
        Method method =
            catalinaDaemon.getClass().getMethod(methodName, paramTypes);
        if (log.isDebugEnabled()) {
            log.debug("Calling startup class " + method);
        }
        //通过反射的方式调用catalina中的load方法
        method.invoke(catalinaDaemon, param);
    }


    /**
     * getServer() for configtest
     */
    private Object getServer() throws Exception {

        String methodName = "getServer";
        Method method = catalinaDaemon.getClass().getMethod(methodName);
        return method.invoke(catalinaDaemon);
    }


    // ----------------------------------------------------------- Main Program


    /**
     * Load the Catalina daemon.
     * @param arguments Initialization arguments
     * @throws Exception Fatal initialization error
     */
    public void init(String[] arguments) throws Exception {

        init();
        load(arguments);
    }


    /**
     * Start the Catalina daemon.
     * @throws Exception Fatal start error
     * 启动Catalina守护进程
     */
    public void start() throws Exception {
        //在init的时候进行赋值，如果为空则重新执行init方法
        if (catalinaDaemon == null) {
            init();
        }

        Method method = catalinaDaemon.getClass().getMethod("start", (Class [])null);
        //通过反射的方式调用catalina中的start方法
        method.invoke(catalinaDaemon, (Object [])null);
    }


    /**
     * Stop the Catalina Daemon.
     * @throws Exception Fatal stop error
     * 停止Catalina后台
     */
    public void stop() throws Exception {
        Method method = catalinaDaemon.getClass().getMethod("stop", (Class []) null);
        method.invoke(catalinaDaemon, (Object []) null);
    }


    /**
     * Stop the standalone server.
     * @throws Exception Fatal stop error
     * 停止standalone server
     */
    public void stopServer() throws Exception {

        Method method =
            catalinaDaemon.getClass().getMethod("stopServer", (Class []) null);
        method.invoke(catalinaDaemon, (Object []) null);
    }


   /**
     * Stop the standalone server.
     * @param arguments Command line arguments
     * @throws Exception Fatal stop error
     */
    public void stopServer(String[] arguments) throws Exception {

        Object param[];
        Class<?> paramTypes[];
        if (arguments == null || arguments.length == 0) {
            paramTypes = null;
            param = null;
        } else {
            paramTypes = new Class[1];
            paramTypes[0] = arguments.getClass();
            param = new Object[1];
            param[0] = arguments;
        }
        Method method =
            catalinaDaemon.getClass().getMethod("stopServer", paramTypes);
        method.invoke(catalinaDaemon, param);
    }


    /**
     * Set flag.
     * @param await <code>true</code> if the daemon should block
     * @throws Exception Reflection error
     * 是否阻塞Catalina的后台
     */
    public void setAwait(boolean await)
        throws Exception {

        Class<?> paramTypes[] = new Class[1];
        paramTypes[0] = Boolean.TYPE;
        Object paramValues[] = new Object[1];
        paramValues[0] = Boolean.valueOf(await);
        //通过反射的方式调用catalina中的setAwait方法
        Method method =
            catalinaDaemon.getClass().getMethod("setAwait", paramTypes);
        method.invoke(catalinaDaemon, paramValues);
    }

    public boolean getAwait() throws Exception {
        Class<?> paramTypes[] = new Class[0];
        Object paramValues[] = new Object[0];
        Method method =
            catalinaDaemon.getClass().getMethod("getAwait", paramTypes);
        Boolean b=(Boolean)method.invoke(catalinaDaemon, paramValues);
        return b.booleanValue();
    }


    /**
     * Destroy the Catalina Daemon.
     */
    public void destroy() {

        // FIXME

    }


    /**
     * Main method and entry point when starting Tomcat via the provided
     * scripts.
     *
     * @param args Command line arguments to be processed
     */
    public static void main(String args[]) {
        //加锁，初始化一次daemon
        synchronized (daemonLock) {
            // daemon初始化时为null，经历过下面的赋值之后就是一个已经有属性值的实例，就不再是null 保证BootStrap对象仅初始化一次
            if (daemon == null) {
                // Don't set daemon until init() has completed
                //注意在初始化完成之前不要将其设置给daemon  其是volatile修饰的具有可见性，如果提前赋值可能会导致其他线程拿到的是一个不完整的Bootstrap对象
                Bootstrap bootstrap = new Bootstrap();
                try {
                    //初始化Bootstrap，主要包括实例化Tomcat特有的类加载器和Catalina实例
                    bootstrap.init();
                } catch (Throwable t) {
                    handleThrowable(t);
                    t.printStackTrace();
                    return;
                }
                //将静态变量daemon设置为初始化完成的BootStrap实例 确定在Tomcat关闭时关闭的是同一个Tomcat实例(volatile 具有可见性)
                daemon = bootstrap;
            } else {
                // When running as a service the call to stop will be on a new
                // thread so make sure the correct class loader is used to
                // prevent a range of class not found exceptions.
                Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
            }
        }
        //主要先执行load加载，然后start启动，这里用的就是模板设计模式启动的
        try {
            String command = "start";
            if (args.length > 0) {
                //取第一个启动jvm参数为指令，java org.apache.catalina.startup.Bootstrap start 时，取得为start
                command = args[args.length - 1];
            }
            //如果为startd，当做start处理
            if (command.equals("startd")) {
                args[args.length - 1] = "start";
                daemon.load(args);
                daemon.start();
            //stopd当做stop处理
            } else if (command.equals("stopd")) {
                args[args.length - 1] = "stop";
                daemon.stop();
            //执行完init()方法后会判断启动参数的值, 由于我们采取默认的启动方式, 所以main方法的参数是start, 会进入下面的判断代码块
            //这三个方法都是通过反射的形式调用catalina中的方法
            } else if (command.equals("start")) {
                // 让当前主线程阻塞  类似 countdownLatch.await
                daemon.setAwait(true);
                // 加载初始化各个组件对象
                daemon.load(args);
                // 启动
                daemon.start();
                //当Catalina实例获取失败时,系统退出
                if (null == daemon.getServer()) {
                    // 结束当前正在运行中的java虚拟机 0是正常结束 其他值非正常结束
                    System.exit(1);
                }
            } else if (command.equals("stop")) {
                daemon.stopServer(args);
            } else if (command.equals("configtest")) {
                daemon.load(args);
                if (null == daemon.getServer()) {
                    System.exit(1);
                }
                System.exit(0);
            } else {
                log.warn("Bootstrap: command \"" + command + "\" does not exist.");
            }
        } catch (Throwable t) {
            // Unwrap the Exception for clearer error reporting
            //通过抓取异常退出程序
            if (t instanceof InvocationTargetException &&
                    t.getCause() != null) {
                t = t.getCause();
            }
            handleThrowable(t);
            t.printStackTrace();
            System.exit(1);
        }
    }


    /**
     * Obtain the name of configured home (binary) directory. Note that home and
     * base may be the same (and are by default).
     * @return the catalina home
     */
    public static String getCatalinaHome() {
        return catalinaHomeFile.getPath();
    }


    /**
     * Obtain the name of the configured base (instance) directory. Note that
     * home and base may be the same (and are by default). If this is not set
     * the value returned by {@link #getCatalinaHome()} will be used.
     * @return the catalina base
     */
    public static String getCatalinaBase() {
        return catalinaBaseFile.getPath();
    }


    /**
     * Obtain the configured home (binary) directory. Note that home and
     * base may be the same (and are by default).
     * @return the catalina home as a file
     */
    public static File getCatalinaHomeFile() {
        return catalinaHomeFile;
    }


    /**
     * Obtain the configured base (instance) directory. Note that
     * home and base may be the same (and are by default). If this is not set
     * the value returned by {@link #getCatalinaHomeFile()} will be used.
     * @return the catalina base as a file
     */
    public static File getCatalinaBaseFile() {
        return catalinaBaseFile;
    }


    // Copied from ExceptionUtils since that class is not visible during start
    static void handleThrowable(Throwable t) {
        if (t instanceof ThreadDeath) {
            throw (ThreadDeath) t;
        }
        if (t instanceof StackOverflowError) {
            // Swallow silently - it should be recoverable
            return;
        }
        if (t instanceof VirtualMachineError) {
            throw (VirtualMachineError) t;
        }
        // All other instances of Throwable will be silently swallowed
    }

    // Copied from ExceptionUtils so that there is no dependency on utils
    static Throwable unwrapInvocationTargetException(Throwable t) {
        if (t instanceof InvocationTargetException && t.getCause() != null) {
            return t.getCause();
        }
        return t;
    }

    // Protected for unit testing
    protected static String[] getPaths(String value) {

        List<String> result = new ArrayList<>();
        Matcher matcher = PATH_PATTERN.matcher(value);

        while (matcher.find()) {
            String path = value.substring(matcher.start(), matcher.end());

            path = path.trim();
            if (path.length() == 0) {
                continue;
            }

            char first = path.charAt(0);
            char last = path.charAt(path.length() - 1);

            if (first == '"' && last == '"' && path.length() > 1) {
                path = path.substring(1, path.length() - 1);
                path = path.trim();
                if (path.length() == 0) {
                    continue;
                }
            } else if (path.contains("\"")) {
                // Unbalanced quotes
                // Too early to use standard i18n support. The class path hasn't
                // been configured.
                throw new IllegalArgumentException(
                        "The double quote [\"] character can only be used to quote paths. It must " +
                        "not appear in a path. This loader path is not valid: [" + value + "]");
            } else {
                // Not quoted - NO-OP
            }

            result.add(path);
        }

        return result.toArray(new String[0]);
    }
}
